package com.wtb.listener;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wtb.dao.QqDao;
import com.wtb.dao.RrDao;
import com.wtb.dao.impl.QqDaoImpl;
import com.wtb.dao.impl.RrDaoImpl;
import com.wtb.domain.DataCache;
import com.wtb.pub.WtbException;
import com.wtb.qq.domain.QqOauth;
import com.wtb.rr.domain.RrOauth;
import com.wtb.utils.DateUtils;
import com.wtb.utils.JdbcUtils;
import com.wtb.utils.RrTokenUtils;

public class RefreshTokenListener implements ServletContextListener {
	private static final Log log = LogFactory
			.getLog(RefreshTokenListener.class);
	private Timer timer;

	public void contextDestroyed(ServletContextEvent sce) {
		timer.cancel();
	}

	/**
	 * 每天凌晨三天遍历数据库 查看 人人网AccessToken是否过期 如果过期 则根据refreshToken来更新accessToken
	 * 保证在过期前一天更新掉
	 */
	public void contextInitialized(ServletContextEvent sce) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 3);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		Date time = calendar.getTime();
		timer = new Timer(true);
		timer.schedule(new TimerTask() {
			public void run() {
				boolean flag = false;
				RrDao rrDao = new RrDaoImpl();
				QqDao qqDao = new QqDaoImpl();
				HashMap<String, RrOauth> rrMap = new HashMap<String, RrOauth>();
				HashMap<String, QqOauth> qqMap = new HashMap<String, QqOauth>();
				ConcurrentHashMap<String, String> rrlastTime = new ConcurrentHashMap<String, String>();
				ConcurrentHashMap<String, String> qqlastTime = new ConcurrentHashMap<String, String>();
				try {
					List<QqOauth> qqList = qqDao.getAll();
					List<RrOauth> rrList = rrDao.getAll();
					// 更新QQ数据缓存
					for (QqOauth qqOauth : qqList) {
						qqMap.put(qqOauth.getUni(), qqOauth);
						qqlastTime.put(qqOauth.getUni(), DateUtils.systemTime());
					}
					// 更新人人数据缓存
					for (RrOauth rrOauth : rrList) {
						flag = DateUtils.isValidKey(rrOauth.getCreateTime(),rrOauth.getExpires_in());
						if (flag) {
							try {
								rrOauth = RrTokenUtils.refreshAccessToken(rrOauth);
								rrDao.update(rrOauth);
								JdbcUtils.commit();
								rrMap.put(rrOauth.getUni(), rrOauth);
								rrlastTime.put(rrOauth.getUni(), DateUtils.createTime()); // 更新数据缓存中的人人状态最后发送时间MAP
							} catch (Exception e) {
								qqMap.remove(rrOauth.getRef()); // 从QQMap中移除授权信息
								qqlastTime.remove(rrOauth.getRef());
								JdbcUtils.rollback();
								log.error("更新人人AccessToken时异常", e);
								throw new WtbException("更新人人AccessToken时异常", e);
							} finally {
								JdbcUtils.close();
							}
						}else {
							rrMap.put(rrOauth.getUni(), rrOauth);
							rrlastTime.put(rrOauth.getUni(), DateUtils.createTime()); // 更新数据缓存中的人人状态最后发送时间MAP
						}
					}
				} catch (Exception e) {
					log.error(e);
					throw new WtbException("更新数据缓存异常", e);
				} finally {
					JdbcUtils.close();
				}

				// 重建数据缓存
				
				 if (qqMap.size() == rrMap.size() && qqMap.size() != 0) {
					try {
						synchronized (DataCache.rrmap) {
							DataCache.RR_MAP_FLAG = true;
							DataCache.rrmap = rrMap;
						}
						synchronized (DataCache.qqmap) {
							DataCache.QQ_MAP_FLAG = true;
							DataCache.qqmap = qqMap;
						}
						synchronized (DataCache.rrlastTime) {
							DataCache.RR_TIME_FLAG = true;
							DataCache.rrlastTime = rrlastTime;
						}
						synchronized (DataCache.qqlastTime) {
							DataCache.QQ_TIME_FLAG = true;
							DataCache.qqlastTime = qqlastTime;
						}
						log.info("重建数据缓存成功！");
					} catch (Exception e) {
						log.error("重建数据缓存失败", e);
						DataCache.RR_MAP_FLAG = false;
						DataCache.QQ_MAP_FLAG = false;
						DataCache.RR_TIME_FLAG = false;
						DataCache.QQ_TIME_FLAG = false;
					}
				}
				 
			}

		}, time);

	}

}
